﻿using DeviceFaultPushService.SystemService;
using System.Collections;
using System.Speech.Synthesis;

namespace DeviceFaultPushService.MessagePushService
{
    public class PlayService
    {
        /// <summary>
        /// 报警队列
        /// </summary>
        private static Queue TaskQueue { get; set; }

        private static SpeechSynthesizer synthesizer;

        public static void Add(string msg)
        {
            if (GetConfiguration.Configuration.EnableVoiceBroadcastingService == false)
            {
                return;
            }
            if (TaskQueue is not null)
            {
                TaskQueue.Enqueue(msg);
            }
            else
            {
                TaskQueue = new();
                TaskQueue.Enqueue(msg);
            }
        }

        /// <summary>
        /// 开启语音播报服务
        /// </summary>
        public static void StartService()
        {
            new Task(() =>
            {
                while (true)
                {
                    if (TaskQueue is not null && TaskQueue.Count >= 1)
                    {
                        string text = TaskQueue.Dequeue().ToString();

                        synthesizer = new SpeechSynthesizer();

                        // 设置输出到默认音频设备
                        synthesizer.SetOutputToDefaultAudioDevice();
                        synthesizer.Volume = 100; // 设置音量（范围从 0-100）
                        synthesizer.Rate = 0; // 设置速度（正数表示加快，负数表示降低）

                        // 订阅播报完成事件  
                        synthesizer.SpeakCompleted += Synthesizer_SpeakCompleted;

                        // 将文本转换为语音并输出到默认音频设备上
                        // 开始异步播报  
                        synthesizer.Speak(text);
                    }
                    Thread.Sleep(3);
                }
            }).Start();
        }

        private static void Synthesizer_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
        {
            // 检查是否成功完成  
            if (e.Error == null)
            {
                // 在这里添加你需要在播报完成后执行的代码，比如退出程序  
                synthesizer.Dispose();
                synthesizer = null;
            }

        }
    }
}
